<template>
  <div>
    <div style="margin-top:20px;display:flex;margin-left:50px;width: 500px">
      <el-button type="info" disabled>班级选择</el-button>
      <el-col :span="1"></el-col>
      <el-select v-model="value" @change="Choose" placeholder="请选择" >
        <el-option
          v-for="item in choose"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </div>
    <div style="display: flex;flex-wrap:wrap;">
      <el-card class="box-card" v-for="i in task" :key="i">
        <div slot="header" class="clearfix">
          <el-dropdown style="float: right; padding: 3px 0" >
            <el-button  type="primary" icon="el-icon-more" ></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="delete_task(i)">删除</el-dropdown-item>
              <el-dropdown-item>移动到</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="text title">
            {{i.title}}
          </div>
          <el-row class="text item" style="margin-top: 30px;justify-content: center;line-height:40px" :gutter="20">
            <el-col :span="4"  >{{'开始时间'}}</el-col>
            <el-col :span="8"><el-tag  effect="plain" size="medium" >{{i.starttime}}</el-tag></el-col>
          </el-row>
          <el-row class="text item" style="justify-content: center;line-height:40px" :gutter="20">
            <el-col :span="4"  >{{'截止时间'}}</el-col>
            <el-col :span="8"><el-tag type="danger" effect="plain" size="medium" >{{i.endtime}}</el-tag></el-col>
          </el-row>
        </div>
        <div class="text item">
          <el-row>
            <el-col :span="12"><el-button round>38份待交</el-button></el-col>
            <el-col :span="8"><el-button type="warning" @click="dialogFormVisible = true">重设发放</el-button></el-col>
            <el-dialog title="重设发放" :visible.sync="dialogFormVisible">
              <el-container style="height: 500px; border: 1px solid #eee">
                <el-main>
                  <el-form :model="form">
                    <el-form-item label="活动名称" :label-width="formLabelWidth">
                      <el-input v-model="form.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="活动区域" :label-width="formLabelWidth">
                      <el-select v-model="form.region" placeholder="请选择活动区域">
                        <el-option label="区域一" value="shanghai"></el-option>
                        <el-option label="区域二" value="beijing"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
                  </div>
                </el-main>
              </el-container>
            </el-dialog>
            <el-col :span="4">
              <router-link :to="{path: '/article/visit', query: {task_id: i._id,task_title: i.title}}">
                <el-button type="success" >查 看</el-button>
              </router-link>
            </el-col>
          </el-row>
        </div>
      </el-card>
      <el-card class="box-card" style="text-align:center;">
        <i class="el-icon-circle-plus-outline" @click="add = true" style="font-size: 600%;color: #409EFF;margin-top:16%"></i>
      </el-card>
      <el-dialog title="发布" :visible.sync="add" width="58%">
        <el-container style="height: 500px; border: 1px solid #eee">
          <el-main>
            <el-form :model="form" >
              <el-form-item label="任务名称" :label-width="formLabelWidth">
                <el-input v-model="form.task_title" autocomplete="off"></el-input>
                <el-link type="info" disabled>若不填写则默认为自拟题目</el-link>
              </el-form-item>
              <el-form-item label="作文题目" :label-width="formLabelWidth">
                <el-input v-model="form.title" autocomplete="off"></el-input>
                <el-link type="info" disabled>若不填写则默认为自拟题目</el-link>
              </el-form-item>
              <el-form-item label="要求" :label-width="formLabelWidth">
                <el-input v-model="form.require" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="提示" :label-width="formLabelWidth">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="form.tips">
                </el-input>
                <el-upload
                  class="upload-demo"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  multiple
                  :limit="3"
                  :on-exceed="handleExceed"
                  :file-list="form.fileList">
                  <el-button size="medium " type="primary" style="margin-top: 15px">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">最多上传三个文件，建议不超过1MB</div>
                </el-upload>
              </el-form-item>
              <el-form-item label="关键词" :label-width="formLabelWidth">
                <el-input v-model="form.keyword" autocomplete="off"></el-input>
                <el-link type="info" disabled>多个关键词用;隔开</el-link>
              </el-form-item>
              <el-form-item label="体裁" :label-width="formLabelWidth">
                <el-select v-model="form.genre" placeholder="请选择体裁">
                  <el-option label="议论文" value="shanghai"></el-option>
                  <el-option label="说明文" value="beijing"></el-option>
                  <el-option label="记叙文" value="shanghai"></el-option>
                  <el-option label="应用文" value="beijing"></el-option>
                </el-select>
              </el-form-item>
              <el-form :inline="true">
                <el-form-item label="学生水平" :label-width="formLabelWidth">
                  <el-select v-model="form.studentlevel" placeholder="请选择学生水平">
                    <el-option label="初级" value="shanghai"></el-option>
                    <el-option label="中级" value="beijing"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="学习者水平" :label-width="formLabelWidth">
                  <el-select v-model="form.studylevel" placeholder="请选择学习者水平">
                    <el-option label="初级" value="shanghai"></el-option>
                    <el-option label="说明文" value="beijing"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <el-form :inline="true">
                <el-form-item label="一级主题" :label-width="formLabelWidth">
                  <el-select v-model="form.firsttopic" placeholder="请选择一级主题">
                    <el-option label="初级" value="shanghai"></el-option>
                    <el-option label="中级" value="beijing"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="二级主题" :label-width="formLabelWidth">
                  <el-select v-model="form.secondtopic" placeholder="请选择二级主题">
                    <el-option label="初级" value="shanghai"></el-option>
                    <el-option label="说明文" value="beijing"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="三级主题" :label-width="formLabelWidth">
                  <el-select v-model="form.thirdtopic" placeholder="请选择三级主题">
                    <el-option label="初级" value="shanghai"></el-option>
                    <el-option label="说明文" value="beijing"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <el-form>
                <el-form-item label="时间安排" :label-width="formLabelWidth">
                  <el-date-picker
                    v-model="form.date"
                    type="datetimerange"
                    align="right"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :default-time="['12:00:00', '08:00:00']">
                  </el-date-picker>
                </el-form-item>
              </el-form>
              <el-form :inline="true">
                <el-form-item label="写作限时" :label-width="formLabelWidth">
                  <el-input v-model="form.timelimit" placeholder="单位为分钟" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="字数要求" :label-width="formLabelWidth">
                  <el-input v-model.number="form.wordlimit" placeholder="**字以上" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="提交方式" :label-width="formLabelWidth">
                  <el-select v-model="form.submitway" placeholder="请选择提交方式">
                    <el-option label="在线提交" value="shanghai"></el-option>
                    <el-option label="线下提交" value="shanghai"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </el-form>
          </el-main>
        </el-container>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetadd('form')">取 消</el-button>
          <el-button type="success" @click="dialoguelead = true">从作文库导入</el-button>
          <el-button type="primary" @click="submitadd(form)">发 布</el-button>
        </div>
      </el-dialog>
      <el-dialog title="从作文库导入" :visible.sync="dialoguelead">
        <div  style="display: flex; width: 400px">
          <el-input v-model="search" placeholder="请输入作文题目" ></el-input>
          <el-col :span="1"></el-col>
          <el-button type="primary" icon="el-icon-search" @click="zuowenkulead(search)">搜索</el-button>
        </div>
        <el-table
          :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
          border
          style="width: 100% ;top: 25px">
          <el-table-column
            prop="id"
            label="序号"
            width="70">
          </el-table-column>
          <el-table-column
            prop="title"
            label="题目"
            width="150">
          </el-table-column>
          <el-table-column
            prop="tips"
            label="提示"
            width="220">
          </el-table-column>
          <el-table-column
            prop="requirement"
            label="要求"
            width="220">
          </el-table-column>
          <el-table-column
            prop="keys"
            label="关键词"
            width="150">
          </el-table-column>
          <el-table-column
            prop="theme"
            label="体裁"
            width="150">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-link type="primary" size="small" @click="importzw(scope.row)">导入</el-link>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: center;margin-top: 30px;">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="num"
            :page-size="pageSize"
            :page-count="10"
            @current-change="current_change">
          </el-pagination>
        </div>
      </el-dialog>
    </div>
    <div style="margin-top: 50px"></div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { BaaS } from '@/api/user'
import dayjs from 'dayjs'
var baas = BaaS()

export default {
  data() {
    return {
      num: 1, //数据条数,
      pageSize: 3,
      currentPage: 1,
      dialogFormVisible: false,
      add: false,
      dialoguelead: false, //从作文库导入对话框
      choose: null,
      search: null, //搜索
      tableData:  //搜索结果
        [{
          id: 'NULL',
          title: 'NULL', //作文题目
          requirement: 'NULL', //要求
          keys: 'NULL', //关键词
          tips: 'NULL', //提示
          theme: 'NULL' //体裁
        }],
      value: '',  //班级编号
      task: '', //作文任务
      form: {
        task_title: '', //任务名称
        title: '', //作文题目
        require: '', //要求
        keyword: '', //关键词
        tips: '', //提示
        genre: '', //体裁
        studentlevel: '', //学生水平
        studylevel: '', //学习者水平
        firsttopic: '', //一级主题
        secondtopic: '', //二级主题
        thirdtopic: '', //三级主题
        timelimit: '', //写作限时
        wordlimit: '', //字数要求
        date: '', //日期
        submitway: '', //提交方式
        zuowenID: '', //作文ID
        fileList: [] //文件
      },
      formLabelWidth: '120px'
    }
  },
  computed: {
    ...mapGetters([
      'currentUser'
    ])
  },
  created() {
    //打印下获得数据结果
    console.log(this.currentUser)
    var BaaS = require('minapp-sdk')
    BaaS.init(baas)
    var query = new BaaS.Query()
    query.compare('teacher_id', '=', this.currentUser.id.toString())
    var Product = new BaaS.TableObject('class')
    Product.setQuery(query).find().then(res => {
      // success
      var classname = []
      for (var i = 0; i < res.data.objects.length; i++) {
        // var dict ={}
        // dict.set{'value',res.data().objects[i].class_name}
        classname.push({   //类似于JS添加JSON的字典方法，Key对应键值，value对应值
          'label': res.data.objects[i].class_name,
          'value': res.data.objects[i].id
        })
        console.log(res.data.objects)
      }
      this.value = res.data.objects[0].id //选择器初值
      console.log(res.data.objects[0].id)
      this.choose = classname
      this.Choose()
    }, err => {
      // err
      console.log(err)
    })
  },
  methods: {
    delete_task(task) { //删除任务
      console.log(task)
      const h = this.$createElement
      this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var BaaS = require('minapp-sdk')
        BaaS.init(baas)
        var Product = new BaaS.TableObject('teacher_task')
        Product.delete(task.id).then(res => {
          // success
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.Choose(this.value)
          var zwzy = new BaaS.TableObject('zuowenzuoye')
          var query = new BaaS.Query()
          query.compare('teacher_task', '=', task._id)
          zwzy.limit(150).offset(0).delete(query).then(res => {
            console.log(res)
            this.$notify({
              title: '删除成功！',
              message: h('i', { style: 'color: red' }, '该作业已经被撤回，学生将不能阅览此作业！！')
            })
          }, err => {
            this.$message.error('错了哦，未知错误，删除失败')
          })
        }, err => {
          // err
          this.$message.error('错了哦，删除失败')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`)
    },
    // visit() {
    //   this.$router.push({
    //     path: '/article/visit',
    //     params: {
    //       id: '123'
    //     }
    //   })
    // },
    submitadd(formName) {  //发布提交
      var BaaS = require('minapp-sdk')
      BaaS.init(baas)
      var Product = new BaaS.TableObject('teacher_task')
      var product = Product.create()
      var add_data = {
        zuowenID: this.form.zuowenID,
        teacher_id: this.currentUser.id.toString(),
        class_id: this.value,
        title: formName.task_title,
        start_date: dayjs(formName.date[0]).toISOString(),
        end_date: dayjs(formName.date[1]).toISOString()
      }
      product.set(add_data).save().then(res => {
        // success
        var taskID = res.data._id
        this.add = false
        const h = this.$createElement
        this.$notify({
          title: '发布成功！',
          message: h('i', { style: 'color: teal' }, '新的作文任务已发布到班级中啦')
        })
        this.Choose(this.value)
        var zwb = new BaaS.TableObject('zuowenban')  //从zuowenban表获取作文班ID
        var query = new BaaS.Query()
        query.compare('class_id', '=', this.value)
        zwb.setQuery(query).find().then(res => {  //zuowenbanID
          // success
          var zwzy = []
          for (var i = 0; i < res.data.objects.length; i++) {
            // var dict ={}
            // dict.set{'value',res.data().objects[i].class_name}
            zwzy.push({   //类似于JS添加JSON的字典方法，Key对应键值，value对应值
              'teacher_task': taskID,
              'zuowenban_id': res.data.objects[i]._id,
              'stu_id': res.data.objects[i].user_id,
              'zuowenID': this.form.zuowenID,
              'iscomplete': false
            })
          }
          console.log(zwzy)
          var zuowenzuoye = new BaaS.TableObject('zuowenzuoye')
          zuowenzuoye.createMany(zwzy).then(res => {
            console.log(res.data.succeed)
            //this.form.zuowenID = ''
            this.$notify({
              title: '布置成功！',
              message: h('i', { style: 'color: teal' }, '班级里的同学可以查看作业详情啦')
            })
          }, err => {
            //err 为 HError 对象
          })
        }, err => {
          // err
        })
      }, err => {
        //err 为 HError 对象
        console.log(err)
      })
    },
    resetadd(formName) {
      this.add = false
    },
    Choose(value) {  //选择班级
      //console.log(this.value)
      this.studenttable = []
      var BaaS = require('minapp-sdk')
      BaaS.init(baas)
      var query = new BaaS.Query()
      query.compare('teacher_id', '=', this.currentUser.id.toString())
      //console.log(this.currentUser)
      query.compare('class_id', '=', this.value)
      var Product = new BaaS.TableObject('teacher_task')
      Product.setQuery(query).find().then(res => {
        // success
        for (var i = 0; i < res.data.objects.length; i++) {
          console.log(res.data.objects[i].start_date)
          var start_date = res.data.objects[i].start_date
          var end_date = res.data.objects[i].end_date
          res.data.objects[i].starttime = dayjs(start_date).format('YYYY-MM-DD dddd')
          res.data.objects[i].endtime = dayjs(end_date).format('YYYY-MM-DD dddd')
        }
        this.task = res.data.objects
      }, err => {
        // err
        console.log(err)
      })
    },
    zuowenkulead(search) { //从作文库导入
      if (search == null) {
        this.$message.error('错了哦，输入为空！')
      }
      var BaaS = require('minapp-sdk')
      BaaS.init(baas)
      var Product = new BaaS.TableObject('zuowenku')
      var query = new BaaS.Query()
      query.compare('title', '=', search)
      Product.setQuery(query).count().then(num => {
        this.num = num
        console.log(num)
        if (num == 0){
          this.$message.error('没有找到该作文题目')
          this.tableData = [{
            id: 'NULL',
            title: 'NULL', //作文题目
            requirement: 'NULL', //要求
            keys: 'NULL', //关键词
            tips: 'NULL', //提示
            theme: 'NULL' //体裁
          }]
        } else {
          this.$message({
            message: '搜索成功',
            type: 'success'
          })
          Product.setQuery(query).find().then(res => {
            // success
            console.log(res.data.objects)
            this.tablejson = res.data.objects
            var zuowenku = []
            for (var i = 0; i < res.data.objects.length; i++) {
              // var dict ={}
              // dict.set{'value',res.data().objects[i].class_name}
              zuowenku.push({   //类似于JS添加JSON的字典方法，Key对应键值，value对应值
                'zuowenID': res.data.objects[i]._id,
                'id': i + 1,
                'title': res.data.objects[i].title,
                'tips': res.data.objects[i].tips,
                'requirement': res.data.objects[i].requirement,
                'keys': res.data.objects[i].keys,
                'learnerlevel': res.data.objects[i].learnerlevel,
                'studentlevel': res.data.objects[i].studentlevel,
                'theme': res.data.objects[i].theme,
                'primarytheme': res.data.objects[i].primarytheme,
                'secondarytheme': res.data.objects[i].secondarytheme,
                'threeleveltheme': res.data.objects[i].threeleveltheme,
                'time': res.data.objects[i].time,
                'wordnum': res.data.objects[i].wordnum
              })
              this.tableData = zuowenku
            }
          }, err => {
            // err
          })
        }
      })
    },
    importzw(row) { //导入
      console.log(row)
      if (row.id != 'NULL'){
        this.$message({
          message: '导入成功',
          type: 'success'
        })
        this.form.title = row.title
        this.form.require = row.requirement
        this.form.keyword = row.keys //关键词
        this.form.tips = row.tips //提示
        this.form.genre = row.theme //体裁
        this.form.studentlevel = row.studentlevel //学生水平
        this.form.studylevel = row.learnerlevel //学习者水平
        this.form.firsttopic = row.primarytheme //一级主题
        this.form.secondtopic = row.secondarytheme //二级主题
        this.form.thirdtopic = row.threeleveltheme //三级主题
        this.form.timelimit = row.time //写作限时
        this.form.wordlimit = row.wordnum //字数要求
        this.form.zuowenID = row.zuowenID //作文ID

        this.dialoguelead = false
      } else {
        this.$message.error('错了哦，信息为空无法导入！')
      }
    }
  }
}
</script>
<style>
.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
.title {
  margin-bottom: 18px;
  font-size: 25px;
  font-weight: bold;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  width: 480px;
  margin-top: 30px;
  margin-left: 50px;
}
.el-dropdown {
  vertical-align: top;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
</style>
